﻿using EF增删改查.DbContexts;
using EF增删改查.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EF增删改查.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class TestController : ControllerBase
    {
        private readonly DefaultDbContext _db;

        public TestController(DefaultDbContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 新增测试
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> AddTestModel(string Info)
        {
            var result = new TestModels();
            result.Info = Info;
            _db.TestModels.Add(result);
            return await _db.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 查询测试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<TestModels>> QueryTestModel()
        {
            return await _db.TestModels.ToListAsync();
        }

        /// <summary>
        /// 更新测试
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> EditTestModel(int Id, string Info)
        {
            var result = await _db.TestModels.Where(x => x.Id == Id).FirstOrDefaultAsync();
            result.Info = Info;
            return await _db.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 删除测试
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteTestModel(int Id)
        {
            var result = await _db.TestModels.Where(x => x.Id == Id).FirstOrDefaultAsync();
            _db.TestModels.Remove(result);

            return await _db.SaveChangesAsync() > 0; ;
        }
    }
}